import { useModel } from "@umijs/max"
import { Button, Card, message, Modal, Row, Slider } from "antd"
import React, { useEffect, useState } from "react"
import { Image, Label, Layer, Rect, Stage, Tag, Text } from "react-konva"

const FourBoxesHandImage: React.FC<{ imageData: string | null }> = ({ imageData }) => {
  const [image, setImage] = useState<HTMLImageElement | null>(null)

  useEffect(() => {
    if (imageData) {
      const img = new window.Image()
      img.src = `data:image/jpeg;base64,${imageData}`
      img.onload = () => {
        setImage(img)
      }
    } else {
      setImage(null)
    }
  }, [imageData])

  return (
    <Image
      image={image}
      width={image ? image.width : 1000}
      height={image ? image.height : 1650}
    />
  )
}

interface PLableProps {
  x: number
  y: number
  name: string
  callBack: (x: number, y: number) => void
}

interface PLableState {
  x: number
  y: number
  name: string
}

class PLable extends React.Component<PLableProps, PLableState> {
  constructor(props: PLableProps) {
    super(props)
    this.state = {
      x: props.x,
      y: props.y,
      name: props.name
    }
  }

  onDragMove = (e: any) => {
    this.setState({
      x: e.target.attrs.x,
      y: e.target.attrs.y
    })
    this.props.callBack(e.target.attrs.x, e.target.attrs.y)
  }

  render() {
    const { x, y, name } = this.state
    return (
      <Label
        x={this.props.x}
        y={this.props.y}
        opacity={0.75} // 透明度
        draggable
        onDragMove={this.onDragMove}
      >
        <Tag
          fill="black"
          pointerDirection="up"
          pointerWidth={10}
          pointerHeight={10}
          lineJoin="round"
          shadowColor="black"
          shadowBlur={10}
          shadowOffset={{ x: 10, y: 10 }}
          shadowOpacity={0.5}
        />
        <Text
          text={name + "  " + x + "  " + y}
          fontFamily="Microsoft YaHei"
          fontSize={18}
          padding={5}
          fill="white"
        />
      </Label>
    )
  }
}

const HandInnerBoard1pinModal: React.FC = () => {
  const {
    handSingleBoxSrc,
    handSingleBoxVisible,
    labelSingleBoxSizeMm,
    labelSingleBoxSizePix,
    updateProduceData
  } = useModel("produceModel")
  const [p1, setP1] = useState({ x: 30, y: 30 })
  const [p2, setP2] = useState({ x: 250, y: 200 })
  
  const [widthAdjustValue, setWidthAdjustValue] = useState(0)
  const [heightAdjustValue, setHeightAdjustValue] = useState(0)
  const [angle_01, setAngle01] = useState(0)
  
  const { callPy } = useModel("websocketModel")
  const { updateWorkStopState } = useModel("deviceModel")

  const closeModal = () => {
    updateProduceData({
      handSingleBoxSrc: null,
      labelSingleBoxSizeMm: [],
      labelSingleBoxSizePix: [],
      handSingleBoxVisible: false
    })
  }

  const handleLabelBoxes4pin = async () => {
    closeModal()
    const args = [
      [[p1.x, p1.y], -angle_01],
    ]
    const response = await callPy("produce", "hand_label_boxes_1pin", args)
    if (!response.state) {
      message.error(response.info, 5)
    }
  }

  const handBoardBack = async () => {
    // Call your API or function here
    const response = await callPy("produce", "board_back_from_web", [])
  }

  const handleReGetImage = async () => {
    closeModal()
    const response = await callPy("produce", "re_get_image_from_web", [])
    if (response.state) {
    }
  }

  const handStopProduce = async () => {
    closeModal()
    updateWorkStopState(true)
    // Call your API or function here
  }

  const handInnerBoardSizeAdjust = async () => {
    const args = [widthAdjustValue, heightAdjustValue]
    closeModal()
    const response = await callPy("produce", "hand_inner_board_1pin_size_adjust", args)
    if (!response.state) {
      message.error("尺寸调整失败: " + response.info, 5)
    }
  }

  return (
    <Modal
      title={"内板位置标注框"}
      open={handSingleBoxVisible}
      width={window.screen.availWidth - 50}
      closable={false}
      footer={null}
      style={{ top: 0, left: 0, right: 0, bottom: 0 }}
    >
      <Card>
        <Card.Grid style={{ width: "70%" }}>
          <Stage width={900} height={660}>
            <Layer>
              <FourBoxesHandImage imageData={handSingleBoxSrc} />
              <Rect
                width={labelSingleBoxSizePix[0]}
                height={labelSingleBoxSizePix[1]}
                strokeWidth={2}
                stroke={"#dfe333"}
                x={p1.x}
                y={p1.y}
                rotation={angle_01}
              />
                <PLable
                x={30}
                y={30}
                key="p1"
                name="1号左上角"
                callBack={(x, y) => {
                  setP1({ x, y })
                }}
              />
              
              <PLable
                x={250}
                y={200}
                key="p2"
                name="1号旋转向下顺时针"
                callBack={(x, y) => {
                  setAngle01((y - p2.y) / 20)
                }}
              />
            </Layer>
          </Stage>
        </Card.Grid>
        <Card.Grid style={{ width: "30%", marginTop: 100}}>
          <Row style={{ marginLeft: 16, marginRight: 16 }}>
            <div>
              <div>
                宽度调整
                <Slider
                  style={{ width: 400 }}
                  value={widthAdjustValue}
                  max={30}
                  min={-30}
                  onChange={setWidthAdjustValue}
                  onChangeComplete={handInnerBoardSizeAdjust}
                />
              </div>
              <div>
                高度调整
                <Slider
                  style={{ width: 400 }}
                  value={heightAdjustValue}
                  max={30}
                  min={-30}
                  onChange={setHeightAdjustValue}
                  onChangeComplete={handInnerBoardSizeAdjust}
                />
              </div>
            </div>
            <div>
              <span style={{ marginRight: 20, marginTop: 30 }}>
                <span style={{ color: "#0000FF", fontSize: 16 }}>
                  标注尺寸:&nbsp;&nbsp;
                </span>
                (宽,高) = ({labelSingleBoxSizeMm[0]},&nbsp;{labelSingleBoxSizeMm[1]})
              </span>
            </div>
          </Row>
          <Row style={{ marginTop: 20, marginLeft: 16 }}>
          
            <Button onClick={handBoardBack} style={{ marginLeft: 20,width:120 }}>
              板回退
            </Button>
            <Button style={{ marginLeft: 20 }} onClick={handleLabelBoxes4pin}>标注</Button>
            </Row>
          <Row style={{ marginTop: 20, marginLeft: 16 }}>
            
            <Button onClick={handleReGetImage} style={{ marginLeft: 20,width:120 }}>
              重新拍照
            </Button>
            <Button style={{ marginLeft: 20 }} onClick={handStopProduce}>
              停止
            </Button>
          </Row>
        </Card.Grid>
      </Card>
    </Modal>
  )
}

export default HandInnerBoard1pinModal
